package com.gpj.sqlbuilder.converters;

import com.gpj.sqlbuilder.constants.Constants;
import com.gpj.sqlbuilder.io.TemplateReader;
import com.gpj.sqlbuilder.store.common.MarkIndex;
import com.gpj.sqlbuilder.store.common.TemplateWraper;
import com.gpj.sqlbuilder.template.*;
import com.gpj.sqlbuilder.utils.TextUtils;

import java.io.InputStream;

/**
 * @className TemplateConverter
 * @description TODO
 * @author GPJ
 * @date 2021/3/31 19:43
 * @version 1.0
 **/
public class TemplateConverter {
	private TemplateReader reader = new TemplateReader();

	public TemplateWraper convert(String name, InputStream io){
		String template = reader.read(io);
		RootTemplate root = new RootTemplate(0, template.length(), template);
		convertTemplate(root.getStart(), root.getTail(), root);
		return new TemplateWraper(name.substring(0, name.lastIndexOf(".")), root);
	}

	private void convertTemplate(int start, int tail, Template template){
		template.getTemplate();
		StringBuffer text = TextUtils.substr(start, tail, template.getTemplate());
		int offset = 0;
		while (offset < text.length()){
			MarkIndex markIndex = TextUtils.findMarkIndex(text,
					Constants.TEMPLATE_START_MARK, Constants.TEMPLATE_TAIL_MARK, offset);
			if(markIndex != null){
				if(markIndex.getStart() != offset){
					template.getChildren().add(
							buildNormalTemplate(offset, markIndex.getStart(), start, template));
				}
				Template child = buildElementTemplate(markIndex.getStart(), markIndex.getEnd(), start, template);
				template.getChildren().add(child);

				offset = child.getTail() - start;
			}else{
				template.getChildren().add(
						buildNormalTemplate(offset, text.length(), start, template));
				break;
			}
		}
	}

	private NormalTemplate buildNormalTemplate(int start, int tail, int offset, Template template){
		return new NormalTemplate(start + offset, tail + offset, template);
	}

	private ElementTemplate buildElementTemplate(int start, int tail, int offset, Template template){
		ElementTemplate elementTemplate = ElementTemplate.createElementTemplate(start + offset, tail + offset, template);
		convertTemplate(elementTemplate.getContentStart(), elementTemplate.getContentEnd(), elementTemplate);
		return elementTemplate;
	}
}
